#include "fxp.h"
#include "defines.h"
#include "rpe_logic.h"

// APCM inverse quatization(5.2.16)
void apcm_iq_of_rpe_seq(int16_t *xMc,int mant, int exp, int16_t* xMp,int k) {
	int16_t temp1,temp2,temp3,temp;
	int i;
	temp1 = table_FAC[mant]; // TODO see 5.2.15 for mant
	temp2= fxp_sub( 6, exp ); // see 5.2.15 for exp
	temp3= 1 << fxp_sub( temp2, 1 );
	for(i=0;i<=12;i++) {
		temp = fxp_sub( ( xMc[i] << 1 ), 7 ); /* See note below */
		temp = temp << 12;
		temp = fxp_mult_r( temp1, temp );
		temp = fxp_add( temp, temp3 );
		xMp[i] = temp >> temp2;
	}
/*
This part is for decoding the RPE sequence of coded xMc[0..12] samples to obtain the xMp[0..12] array. Table 5.6 is
used to get the mantissa of xmaxc (FAC[0..7]).
temp1 = FAC[mant]; see 5.2.15 for mant
temp2= sub( 6, exp ); see 5.2.15 for exp
temp3= 1 << sub( temp2, 1 );
|== FOR i =0 to 12:
| temp = sub( ( xMc[i] << 1 ), 7 ); /See note below/
| temp = temp << 12;
| temp = mult_r( temp1, temp );
| temp = add( temp, temp3 );
| xMp[i] = temp >> temp2;
|== NEXT i;
NOTE: This subtraction is used to restore the sign of xMc[i].
*/
}

// RPE grid positioning(5.2.17)
void rpe_grid_positioning(int16_t* xMp, int Mc, int16_t* ep,int k) {
	int i;
	int k_start,k_end;

	k_start = k * 40;
	k_end = k_start + 39;

	for(i=0;i<40;i++)
		ep[i] = 0;
	 
	for(i=0;i<13;i++)
		ep[k_start+Mc +(3*i)] = xMp[i];
/*
This procedure computes the reconstructed long term residual signal ep[0..39] for the LTP analysis filter. The inputs are
the Mc which is the grid position selection and the xMp[0..12] decoded RPE samples which are upsampled by a factor
of 3 by inserting zero values.
|== FOR k = 0 to 39:
| ep[k] = 0;
ETSI
(GSM 06.10 version 8.1.1 Release 1999) 40 ETSI EN 300 961 V8.1.1 (2000-11)
|== NEXT k:
|== FOR i = 0 to 12:
| ep[Mc +(3*i)] = xMp[i];
|== NEXT i:

 */
}

